<template lang="pug">
.toolbar
  .toolbar-content
    .item(v-for="(item, index) in list" :key="index")
      a-tooltip(placement="bottom")
        template(#title="slot") {{item.label || item.tips}}
        component(:is="item.icon" v-if="item.icon")
        span(v-else @click="toolbarClick(item)") {{item.label}}
  a-modal(
    v-model:visible="getJsonVisible"
    title="预览JSON"
    width="45%"
    cancelText="关闭"
    okText="复制JSON"
    @ok="handleOk"
    @cancel="handleCancel")
    .json-box
      v-ace-editor(
        v-model:value="jsonStr"
        lang="json"
        theme="chrome"
        style="height:100%;"
        :options="{ useWorker: true }")
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { useStore } from "vuex";
import toolList from "./toolList";
import toolbar from "./toolbarFunc";
import { message } from "ant-design-vue";
import { VAceEditor } from "vue3-ace-editor";
import "ace-builds/src-noconflict/mode-json";
import "ace-builds/src-noconflict/theme-chrome";
import ace from "ace-builds";
import workerJsonUrl from "ace-builds/src-noconflict/worker-json?url";
import useClipboard from "vue-clipboard3";
export default defineComponent({
  name: "toolBar",
  components: {
    VAceEditor,
  },
  setup() {
    const { toClipboard } = useClipboard();
    const store = useStore();
    const contentJson = store.state.lowCode.contentJson;
    const list: Array<any> = reactive(toolList);
    const getJsonVisible = ref<boolean>(false);
    const jsonStr = ref("");
    ace.config.setModuleUrl("ace/mode/json_worker", workerJsonUrl);
    async function handleOk() {
      // 复制
      try {
        await toClipboard(jsonStr.value);
        message.success("复制成功");
      } catch (e) {
        console.error(e);
      }
    }
    function handleCancel() {
      getJsonVisible.value = false;
      jsonStr.value = "";
    }
    const toolbarClick = (item: any) => {
      console.log(toolbar, item);
      if (item.key === "preview-json") {
        // 预览json1
        getJsonVisible.value = true;
        jsonStr.value = JSON.stringify(contentJson, null, 2);
      } else if (toolbar[item.key]) {
        toolbar[item.key](contentJson);
      } else {
        message.warning("功能开发中");
      }
    };
    return {
      list,
      toolbarClick,
      getJsonVisible,
      handleOk,
      jsonStr,
      handleCancel,
    };
  },
});
</script>

<style lang="stylus" scoped>
.json-box
  width: 100%
  height: 400px
.toolbar {
  border-bottom: 1px solid #cdd;
  box-sizing: border-box;
  .toolbar-content {
    margin: 0px 20px;
    display: flex;
    align-items: center;
    height: 59px;
    .item {
      cursor: pointer;
      margin-right: 20px;
      i {
        font-size: 20px;
      }
    }
  }
}
</style>
